<template>
  <section>
    <van-sticky>
      <PageHeader title="角色"/>
    </van-sticky>

    <van-form @submit="onFormSubmit">
      <van-field
        v-model="formData.name"
        name="name"
        label="名称"
        placeholder="请输入名称"
        :rules="[{ required: true, message: '请输入名称' }]"
      />

      <van-field
        v-model="formData.remark"
        name="remark"
        label="备注"
        placeholder="请输入备注"
        type="textarea"
        :rows="6"
      />

      <div style="margin: 16px;">
        <van-button round block type="info" native-type="submit">
          保存
        </van-button>
      </div>
    </van-form>

  </section>
</template>

<script>
import PageHeader from "../componets/PageHeader";
import {roleAddUri, roleEditUri, roleInfoUri} from "../../common/api";

export default {
  components: {
    PageHeader
  },
  data() {
    return {
      formData: {id: 0, name: '', remark: ''}
    }
  },
  methods: {
    onFormSubmit(values) {
      const that = this;
      let url = roleAddUri;
      if(this.$route.name == 'RoleEdit') {
        url = roleEditUri;
      }
      that.$http.post(url, that.formData, {emulateJSON: true}).then(response => {
        let {msg, code, data} = response.body
        if (code != 0) {
          that.$toast.fail(msg);
        } else {
          that.$toast.success('保存成功');
          that.$router.back();
        }
      }, response => {
        that.$toast.fail('发生错误');
      })
    },
    getInfo() {
      const that = this;
      this.$http.get(roleInfoUri + '?id=' + this.$route.params.id).then(response => {
        let {code, msg, data} = response.body
        if (code != 0) {
          that.$toast.fail(msg);
        } else {
          that.formData = {id: data.id, name: data.name, remark: data.remark};
        }
      }, response => {
        // error callback
      })
    }
  },
  mounted: function () {
    if(this.$route.name == 'RoleEdit') {
      this.getInfo();
    }
  }
}
</script>

<style scoped>

</style>
